<?php

//get
@include_once('connect.php');
header("Access-Control-Allow-Origin: *");

//前端数据
$res = [];

//合并搜索、排序和分页
//接收数据有搜索关键字、排序类型、排序名称、每页显示数据条数、第几页
$kw = $_GET['kw'];
$orderType = $_GET['orderType'];
$orderName = $_GET['orderName'];
$num = $_GET['num'];
$page = $_GET['page'];
$kw1 = $_GET['kw1'];
// $kw = '手机';
// $orderType = 1;
// $orderName = 'goods_id';
// $num = 5;
// $page = 1;

if ($num && $page) {
    //处理排序
    if ($orderType == 1) {
        $orderType = 'asc';
    } else {
        $orderType = 'desc';
    }

    if ($kw == 1) {
        $kw = '手机';
    } else if ($kw == 2) {
        $kw = '智能穿戴';
    } else if ($kw == 3) {
        $kw = '电视';
    }
    //搜索时排序，得到当搜索商品名称的关键字时得到的商品列表，同时商品列表分页显示，并且可以排序
    $sql = "SELECT COUNT(*) total FROM goods_list1 WHERE good_type LIKE '%$kw%'";
    $ggo = mysqli_query($connect, $sql);
    //得到对象{total:n}
    $arr = mysqli_fetch_array($ggo);
    //定义变量total
    $total = $arr['total'];

    // 标题动态生成
    $sql = "SELECT DISTINCT goods_pattern FROM goods_list1 WHERE good_type LIKE '%$kw%'";
    $ggo = mysqli_query($connect, $sql);
    $list1 = [];
    while ($arr = mysqli_fetch_array($ggo)) {
        array_push($list1, $arr);
    }

    // 内容分类
    $sql = "SELECT * FROM goods_list1 WHERE goods_pattern LIKE '%$kw1%' AND good_type LIKE '%$kw%'";
    $ggo = mysqli_query($connect, $sql);
    $list2 = [];
    while ($arr = mysqli_fetch_array($ggo)) {
        array_push($list2, $arr);
    }

    //开始分页
    //三个条件：商品名称包含关键词、排序、分页限制输出数据
    //排序、分页限制输出数据不加引号
    $start = ($page - 1) * $num;
    $sql = "SELECT * FROM goods_list1 WHERE good_type LIKE '%$kw%' ORDER BY $orderName $orderType LIMIT $start,$num";
    $ggo = mysqli_query($connect, $sql); //结果集

    $list = [];
    while ($arr = mysqli_fetch_array($ggo)) {
        array_push($list, $arr);
    }

    if ($list && $list1) {
        $res['status'] = true;
        $res['msg'] = '请求成功';
        $res['total'] = $total;
        $res['data'] = $list;
        $res['title'] = $list1;
        $res['pattern'] = $list2;
    } else {
        $res['status'] = false;
        $res['msg'] = '数据库错误';
    }
} else {
    $res['status'] = false;
    $res['msg'] = '前端数据错误';
}

echo (json_encode($res, JSON_UNESCAPED_UNICODE));
